import { ProjectsService } from '@/client';
import { Popover, Portal, Text, Link, Button, Flex } from '@chakra-ui/react'
import { useMutation } from '@tanstack/react-query';



export default function DeletePopover({ item, refetch }: { item: { id: string | null; name: string }, refetch: () => void }) {
    const mutation = useMutation({
        mutationFn: () => {
            if (item.id === null) {
                return Promise.reject(new Error('Project ID is null'));
            }
            return ProjectsService.deleteProjectApi({ projectId: item.id });
        },
        onSuccess: () => {
            // Handle successful deletion
        },
        onError: () => {
            // Handle error
        },
        onSettled: () => {
            refetch()
        }
    });

    return (
        <Popover.Root >
            <Popover.Trigger asChild>
                <Link colorPalette="red">
                    删除
                </Link>
            </Popover.Trigger>
            <Portal>
                <Popover.Positioner>
                    <Popover.Content w={'auto'}>
                        <Popover.Arrow />
                        <Popover.Body>
                            <Popover.Title fontWeight="medium" color="red">确认删除？</Popover.Title>
                            <Text fontSize="sm" color="red">删除后将无法找回！</Text>
                        </Popover.Body>
                        <Flex gap={2} p={2}>
                            <Popover.CloseTrigger>

                                <Button colorPalette="gray">取消</Button>
                            </Popover.CloseTrigger>
                            <Button colorPalette="red" onClick={() => mutation.mutate()}>删除</Button>
                        </Flex>
                    </Popover.Content>
                </Popover.Positioner>
            </Portal>
        </Popover.Root>
    );
}
